// 例子20

function a(){
    function foo() {
        setTimeout(() => {
            console.log('id:', this.id);
            console.log('----------------------------------');
            b();
        }, 100);
    }
    var id = 21;
    foo.call({ id: 42 }); // "id: 42"
}

function b(){
    function Timer() {
        this.s1 = 0;
        this.s2 = 0;
        // 箭头函数
        setInterval(() => this.s1++, 1000);
        // 普通函数
        setInterval(function () {
            this.s2++;
        }, 1000);
    }

    var timer = new Timer();

    setTimeout(() => console.log('s1: ', timer.s1), 3100);
    setTimeout(() => {
        console.log('s2: ', timer.s2)
        console.log('----------------------------------');
        c();
    }, 3100);
    // "s1: 3"
    // "s2: 0"
}

function c(){
    // this指向的固定化，有利于封装回调函数
    var handler = {
        id: '123456',

        init: function() {
            document.addEventListener('click', event => this.doSomething(event.type), false);
        },

        doSomething: function(type) {
            console.log('Handling ' + type  + ' for ' + this.id);
        }
    };

    console.log('----------------------------------');

    d();
}

function d(){
    // 箭头函数的实际转化
    {
        // ES6
        function foo() {
            setTimeout(() => {
                console.log('id:', this.id);
            }, 100);
        }

        foo();
    }


    {
        // ES5
        function foo() {
            var _this = this;
            setTimeout(function () {
                console.log('id:', _this.id);
            }, 100);
        }

        foo();
    }
}

a();
